﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HYBYSoft.Company.Models;
using System.Text;
using HYBYSoft.Company.WebSite.Helper;

namespace HYBYSoft.Company.WebSite.Areas.Admin.Controllers
{
    public class LoginController : Controller
    {
        /// <summary>
        /// 数据库实体上下文对象
        /// </summary>
        CompanySiteEntities _dbContext = new CompanySiteEntities();

        /// <summary>
        /// 登录界面Get请求
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 获得验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {
            ValidateCode codeCreater = new ValidateCode();
            string validateCode = codeCreater.CreateValidateCode(5);
            Session["ValidateCode"] = validateCode;
            byte[] bytes = codeCreater.CreateValidateGraphic(validateCode);
            return File(bytes, @"image/jpeg");
        }

        /// <summary>
        /// 登出操作
        /// </summary>
        /// <returns></returns>        
        public ActionResult Logout()
        {
            DeleteCookie(ConstDefinition.TOKEN_NAME);

            return RedirectToAction("Login");
        }

        /// <summary>
        /// 提交用户登录
        /// </summary>
        /// <param name="admin">用户实体对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(HYBYSoft.Company.Models.Admin admin)
        {
            var validateCode = Request["txtValiCode"];
            if (Session["ValidateCode"] == null || validateCode != Session["ValidateCode"].ToString())
            {
                ModelState.AddModelError(string.Empty, "验证码不正确！");
                Session.Remove("ValidateCode");
                return View(admin);
            }

            //清除验证码信息
            Session.Remove("ValidateCode");

            //对登录密码进行MD5加密并进行Base64编码
            string password = SecurityHelper.CreateHashAndBase64(admin.Password);

            var result = _dbContext.Admins.FirstOrDefault(a => a.Name == admin.Name && a.Password == password && a.State != 0);
            if (result != null)
            {
                //编写Cookie信息
                char[] sepatator = new char[] { '$' };
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append(result.AdminID);
                stringBuilder.Append(sepatator);
                stringBuilder.Append(result.Name);
                stringBuilder.Append(sepatator);
                stringBuilder.Append(result.CompanyID);
                stringBuilder.Append(sepatator);
                stringBuilder.Append(DateTime.Now);

                string cookieString = Convert.ToBase64String(
                                Encoding.UTF8.GetBytes(stringBuilder.ToString()));
                //保存Cookie信息
                SetCookie(ConstDefinition.TOKEN_NAME, cookieString);

                return RedirectToAction("Index", "Member");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "用户名或密码不正确！");
            }


            return View(admin);
        }

        /// <summary>
        /// 保存Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">Cookie的值</param>
        [NonAction]
        protected void SetCookie(string key, string value)
        {
            HttpCookie cookie = new HttpCookie(key);
            cookie.Domain = null;
            cookie.Value = value;

            Response.AppendCookie(cookie);
        }

        /// <summary>
        /// 清除Cookie
        /// </summary>
        /// <param name="cookieName">Token名称</param>
        [NonAction]
        protected void DeleteCookie(string cookieName)
        {
            if (Request.Cookies[cookieName] == null) return;

            HttpCookie cookie = new HttpCookie(cookieName);
            cookie.Expires = DateTime.Now.AddDays(-1);
            Response.AppendCookie(cookie);
        }
    }
}
